const style = require('./render/style')
const template = require('./render/template')
const Layout = require('./engine').default;

let __env = GameGlobal.wx || GameGlobal.tt || GameGlobal.swan;
let sharedCanvas  = __env.getSharedCanvas();
let sharedContext = sharedCanvas.getContext('2d');
let datakey = "suanzhu"
function draw(data) {
    Layout.clear();
    Layout.init(template(data), style);
    Layout.layout(sharedContext);
}

function updateViewPort(data) { 
    Layout.updateViewPort({
        x: data.x,
        y: data.y,
        width: data.width,
        height: data.height,
    });
}

function setUserCloudStorage(data){
    __env.setUserCloudStorage({"KVDataList":data,success:(res)=>{
        console.log("setUserCloudStorage success",res);
    },fail:(res)=>{
        console.log("setUserCloudStorage fail",res);
    }});
}

function getUserCloudStorage(){
    __env.getFriendCloudStorage({keyList:[datakey],success:(res)=>{
        console.log("sssss",res);
        let tarr=[];
        if(res.data){
            for(let i=0;i<res.data.length;i++){
                let tobj = res.data[i];
                if (!(tobj.KVDataList.length))
                    continue;
                let kv = tobj.KVDataList[0];
                    if (kv.key != datakey)
                        continue;
                    kv = JSON.parse(kv.value);
                    let listData = {};
                    listData.avatarUrl = tobj.avatarUrl;
                    listData.nickname = tobj.nickname;
                    listData.openid = tobj.openid;
                    listData.gate = kv.gate;
                    tarr.push(listData);
            }
            tarr = tarr.sort(function (a, b) {
                return b.gate - a.gate;
            });
            //增加一个用于查看的index排名
            for (var i = 0; i < tarr.length; i++) {
                tarr[i].index = i + 1;
            }
            
        }
        draw(tarr);
    },fail:(res)=>{console.log("getUserCloudStorage err",res)}});
}

__env.onMessage(data => {
    console.log("onMessage",data);
    if ( data.type === 'engine') {
        if(data.event === 'viewport'){
            updateViewPort(data);
            getUserCloudStorage();
        }else if(data.event === 'user'){
            setUserCloudStorage(data.KVDataList);
        }
    }
});
